<template>
    <div class="listView" v-loading="loading">
        <!-- 时间筛选功能 -->
        <div class="line1">
            <el-button-group>
                <el-button :type="selectedButton === 'today' ? 'primary' : ''" @click="selectDate('today')">当日</el-button>
                <el-button :type="selectedButton === 'last7days' ? 'primary' : ''"
                    @click="selectDate('last7days')">最近7天</el-button>
                <el-button :type="selectedButton === 'last30days' ? 'primary' : ''"
                    @click="selectDate('last30days')">最近30天</el-button>
                <el-button :type="selectedButton === 'lastyear' ? 'primary' : ''"
                    @click="selectDate('lastyear')">最近一年</el-button>
            </el-button-group>

        </div>
        <div class="line2">
            <!-- 整体数据 -->
            <div class="l2Data1">
                <el-card style="height: 100%;">
                    <p class="card-header" slot="header">整体数据</p>
                    <div class="card-main">
                        <div class="card-main-detail" v-if="userInfo.position == 'manager'">
                            <div class="circle-icon4">
                                <i class="icon iconfont icon-customer"></i>
                            </div>
                            <h2>{{ overallData.employeeCount }}</h2>
                            <p>员工数量</p>
                        </div>
                        <div class="card-main-detail" v-if="userInfo.position == 'exhibitor'">
                            <div class="circle-icon4">
                                <i class="icon iconfont icon-store"></i>
                            </div>
                            <h2>{{ overallData.exhibitionCount }}</h2>
                            <p>展厅数量</p>
                        </div>
                        <div class="card-main-detail">
                            <div class="circle-icon2">
                                <i class="icon iconfont icon-product-list"></i>
                            </div>
                            <h2>{{ overallData.modelCount }}</h2>
                            <p>模型数量</p>
                        </div>
                        <div class="card-main-detail" v-if="userInfo.position == 'manager'">
                            <div class="circle-icon1">
                                <i class="icon iconfont icon-discount"></i>
                            </div>
                            <h2>{{ overallData.categoryCount }}</h2>
                            <p>分类数量</p>
                        </div>
                        <div class="card-main-detail" v-if="userInfo.position == 'exhibitor'">
                            <div class="circle-icon1">
                                <i class="icon iconfont icon-company"></i>
                            </div>
                            <h2>{{ overallData.companyCount }}</h2>
                            <p>参展公司数量</p>
                        </div>
                    </div>
                </el-card>
            </div>
            <!-- 用户喜爱数据 -->
            <div class="l2Data2">
                <el-card style="height: 100%;">
                    <p class="card-header" slot="header">用户喜爱数据</p>
                    <div class="card-main">
                        <div class="card-main-detail">
                            <div class="circle-icon2">
                                <i class="icon iconfont icon-product-list"></i>
                            </div>
                            <h2>{{ userFavoriteData.favoriteModel }}</h2>
                            <p>最喜欢的模型</p>
                        </div>
                        <div class="card-main-detail">
                            <div class="circle-icon2">
                                <i class="icon iconfont icon-product-list"></i>
                            </div>
                            <h2>{{ userFavoriteData.mostWatchedModel }}</h2>
                            <p>观看最多的模型</p>
                        </div>
                        <div class="card-main-detail" v-if="userInfo.position == 'manager'">
                            <div class="circle-icon3">
                                <i class="icon iconfont icon-discount"></i>
                            </div>
                            <h2>{{ userFavoriteData.favoriteCategory }}</h2>
                            <p>最喜爱的分类</p>
                        </div>
                        <div class="card-main-detail" v-if="userInfo.position == 'manager'">
                            <div class="circle-icon3">
                                <i class="icon iconfont icon-discount"></i>
                            </div>
                            <h2>{{ userFavoriteData.mostWatchedCategory }}</h2>
                            <p>观看最多的分类</p>
                        </div>
                        <div class="card-main-detail" v-if="userInfo.position == 'exhibitor'">
                            <div class="circle-icon3">
                                <i class="icon iconfont icon-store"></i>
                            </div>
                            <h2>{{ userFavoriteData.favoriteExhibition }}</h2>
                            <p>最喜爱的展厅</p>
                        </div>
                        <div class="card-main-detail" v-if="userInfo.position == 'exhibitor'">
                            <div class="circle-icon3">
                                <i class="icon iconfont icon-store"></i>
                            </div>
                            <h2>{{ userFavoriteData.mostWatchedExhibition }}</h2>
                            <p>观看最多的展厅</p>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>

        <div class="line3">
            <!-- 观看数量趋势 -->
            <div class="l3Data1">
                <el-card style="height: 100%;" v-if="userInfo.position == 'manager'">
                    <p class="card-header" slot="header">模型观看数量趋势</p>
                    <div id="modelLineChart" style="height: 100%;"></div>
                </el-card>
                <el-card style="height: 100%;" v-if="userInfo.position == 'exhibitor'">
                    <p class="card-header" slot="header">展厅观看数量趋势</p>
                    <div id="exhibitionLineChart" style="height: 100%;"></div>
                </el-card>
            </div>
            <div class="l3Data2" style="display: flex; gap: 10px;flex-direction: column;">
                <!-- 模型喜爱数据 -->
                <el-card style="height: 50%">
                    <p class="card-header" slot="header">模型喜爱数据</p>
                    <div v-if="!this.modelPieChartOptionNull" id="modelPieChart" style="height: 100%;"></div>
                    <h2 v-if="this.modelPieChartOptionNull">暂无数据</h2>
                </el-card>
                <!-- 类型喜爱数据 -->
                <el-card style="height: 50%" v-if="userInfo.position == 'manager'">
                    <p class="card-header" slot="header">类型喜爱数据</p>
                    <div v-if="!this.categoryPieChartOptionNull" id="categoryPieChart" style="height: 100%;"></div>
                    <h2 v-if="this.categoryPieChartOptionNull">暂无数据</h2>
                </el-card>
                <!-- 展厅喜爱数据 -->
                <el-card style="height: 50%" v-if="userInfo.position == 'exhibitor'">
                    <p class="card-header" slot="header">展厅喜爱数据</p>
                    <div v-if="!this.exhibitionPieChartOptionNull" id="exhibitionPieChart" style="height: 100%;"></div>
                    <h2 v-if="this.exhibitionPieChartOptionNull">暂无数据</h2>
                </el-card>
            </div>
        </div>
    </div>
</template> 

<script>
import echarts from 'echarts';
import { getAnalytics } from '../../api/analytics'; // 导入需要的API函数

export default {
    data() {
        return {
            loading: true,
            value1: [],
            selectedButton: 'today', // 默认选中当日按钮
            usedColors: [],

            availableColors: ['#91CC75', '#FAC858', '#5470C7', '#74C0DE'],

            selectedDate: null,
            overallData: {
                employeeCount: 0, // 示例数据，请替换为实际数据
                exhibitionCount: 0, // 示例数据，请替换为实际数据
                modelCount: 0, // 示例数据，请替换为实际数据
                companyCount: 0, // 示例数据，请替换为实际数据
                categoryCount: 0,
            },
            userFavoriteData: {
                favoriteModel: 'Model A', // 示例数据，请替换为实际数据
                mostWatchedModel: 'Model B', // 示例数据，请替换为实际数据
                favoriteCategory: 'Category X', // 示例数据，请替换为实际数据
                mostWatchedCategory: 'Category Y', // 示例数据，请替换为实际数据
                favoriteExhibition: 'Exhibition X',
                mostWatchedExhibition: 'Exhibition Y'
            },
            analyticsData: [],

            modelPieChartOption: {
                legend: {
                    data: [], // 初始为空，将在init方法中更新
                    orient: 'horizontal',
                    x: 'center',
                    y: 'top',
                    itemGap: 40,
                    itemHeight: 10
                },
                series: [
                    {
                        name: '模型收藏人数',
                        type: 'pie',
                        radius: '55%',
                        data: [],
                    },
                ],
            },
            modelPieChartOptionNull: false,

            categoryPieChartOption: {
                legend: {
                    data: [], // 初始为空，将在init方法中更新
                    orient: 'horizontal',
                    x: 'center',
                    y: 'top',
                    itemGap: 40,
                    itemHeight: 10
                },
                series: [
                    {
                        name: '类型收藏人数',
                        type: 'pie',
                        radius: '55%',
                        data: [],
                    },
                ],
            },
            categoryPieChartOptionNull: false,

            exhibitionPieChartOption: {
                legend: {
                    data: [], // 初始为空，将在init方法中更新
                    orient: 'horizontal',
                    x: 'center',
                    y: 'top',
                    itemGap: 40,
                    itemHeight: 10
                },
                series: [
                    {
                        name: '展厅收藏人数',
                        type: 'pie',
                        radius: '55%',
                        data: [],
                    },
                ],
            },
            exhibitionPieChartOptionNull: false,

            modelLineChartOption: {
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: [], // 初始为空，将在init方法中更新
                },
                yAxis: {
                    type: 'value',
                },
                legend: {
                    data: ['模型总观看人数'], // 添加图例名称
                    orient: 'horizontal',
                    x: 'center',
                    y: 'top',
                    itemGap: 40,
                    itemHeight: 10,
                },
                series: [
                    {
                        name: '模型总观看人数',
                        data: [], // 初始为空，将在init方法中更新
                        type: 'line',
                        color: ['#5DB1FF'],
                        areaStyle: {},
                        symbolSize: 7,
                        smooth: true
                    },
                ],
            },
            modelLineChartOptionNull: false,

            exhibitionLineChartOption: {
                xAxis: {
                    type: 'category',
                    data: [], // 初始为空，将在init方法中更新
                },
                yAxis: {
                    type: 'value',
                    boundaryGap: false,
                },
                legend: {
                    data: ['展厅总观看人数'], // 添加图例名称
                    orient: 'horizontal',
                    x: 'center',
                    y: 'top',
                    itemGap: 40,
                    itemHeight: 10,
                },
                series: [
                    {
                        name: '展厅总观看人数',
                        data: [], // 初始为空，将在init方法中更新
                        type: 'line',
                        color: ['#5DB1FF'],
                        areaStyle: {},
                        symbolSize: 7,
                        smooth: true
                    },
                ],
            },
            exhibitionLineChartOptionNull: false,
        };
    },
    created() {
        this.init("today");
        const userInfo = window.localStorage.getItem("userInfo");
        if (userInfo) {
            this.userInfo = JSON.parse(userInfo);
        }
        if (this.userInfo.position === "exhibitor") {
            console.log("展厅管理员驾到，统统闪开")
        }
    },
    mounted() {

    },
    methods: {
        async init(chosenDate) {
            const params = {
                chosenDate: chosenDate,
            };
            try {
                this.loading = true
                const res = await getAnalytics(params);
                if (String(res.code) === '1') {
                    this.analyticsData = res.data || [];
                    this.overallData.employeeCount = this.analyticsData.employeeNum
                    this.overallData.modelCount = this.analyticsData.modelNum
                    this.overallData.companyCount = this.analyticsData.companyNum
                    this.overallData.categoryCount = this.analyticsData.categoryNum

                    this.overallData.exhibitionCount = this.analyticsData.exhibitionNum

                    this.userFavoriteData.favoriteModel = this.analyticsData.favoriteModel;
                    this.userFavoriteData.mostWatchedModel = this.analyticsData.mostWatchedModel;
                    this.userFavoriteData.favoriteCategory = this.analyticsData.favoriteCategory;
                    this.userFavoriteData.mostWatchedCategory = this.analyticsData.mostWatchedCategory;
                    this.userFavoriteData.favoriteExhibition = this.analyticsData.favoriteExhibition;
                    this.userFavoriteData.mostWatchedExhibition = this.analyticsData.mostWatchedExhibition;

                    if (this.userFavoriteData.favoriteModel === null) {
                        this.userFavoriteData.favoriteModel = "暂无数据"
                    }
                    if (this.userFavoriteData.mostWatchedModel === null) {
                        this.userFavoriteData.mostWatchedModel = "暂无数据"
                    }
                    if (this.userFavoriteData.favoriteCategory === null) {
                        this.userFavoriteData.favoriteCategory = "暂无数据"
                    }
                    if (this.userFavoriteData.mostWatchedCategory === null) {
                        this.userFavoriteData.mostWatchedCategory = "暂无数据"
                    }
                    if (this.userFavoriteData.favoriteExhibition === null) {
                        this.userFavoriteData.favoriteExhibition = "暂无数据"
                    }
                    if (this.userFavoriteData.mostWatchedExhibition === null) {
                        this.userFavoriteData.mostWatchedExhibition = "暂无数据"
                    }

                    // 更新饼图配置
                    this.modelPieChartOption.legend.data = this.analyticsData.modelPieChartOption.map(item => item.name);

                    this.modelPieChartOption.series[0].data = this.analyticsData.modelPieChartOption.map(item => ({
                        name: item.name,
                        value: item.count,
                        itemStyle: { color: this.getRandomColor() },
                    }));
                    if (this.analyticsData.modelPieChartOption.length == 0) {
                        this.modelPieChartOptionNull = true
                    } else {
                        this.modelPieChartOptionNull = false
                    }
                    // 重置已使用颜色数组
                    this.usedColors = [];

                    // 更新饼图配置
                    this.categoryPieChartOption.legend.data = this.analyticsData.categoryPieChartOption.map(item => item.name);

                    this.categoryPieChartOption.series[0].data = this.analyticsData.categoryPieChartOption.map(item => ({
                        name: item.name,
                        value: item.count,
                        itemStyle: { color: this.getRandomColor() },
                    }));


                    if (this.analyticsData.categoryPieChartOption.length == 0) {
                        this.categoryPieChartOptionNull = true
                    } else {
                        this.categoryPieChartOptionNull = false
                    }
                    // 重置已使用颜色数组
                    this.usedColors = [];

                    // 更新饼图配置
                    this.exhibitionPieChartOption.legend.data = this.analyticsData.exhibitionPieChartOption.map(item => item.name);

                    this.exhibitionPieChartOption.series[0].data = this.analyticsData.exhibitionPieChartOption.map(item => ({
                        name: item.name,
                        value: item.count,
                        itemStyle: { color: this.getRandomColor() },
                    }));

                    console.log("this.analyticsData.exhibitionPieChartOption.length:" + this.analyticsData.exhibitionPieChartOption.length)
                    if (this.analyticsData.exhibitionPieChartOption.length == 0) {
                        this.exhibitionPieChartOptionNull = true
                    } else {
                        this.exhibitionPieChartOptionNull = false
                    }
                    // 重置已使用颜色数组
                    this.usedColors = [];

                    // 更新折线图配置
                    this.exhibitionLineChartOption.xAxis.data = this.analyticsData.exhibitionLineChartOption.map(item => item.date);
                    this.exhibitionLineChartOption.series[0].data = this.analyticsData.exhibitionLineChartOption.map(item => item.viewCount);

                    // 更新折线图配置
                    this.modelLineChartOption.xAxis.data = this.analyticsData.modelLineChartOption.map(item => item.date);
                    this.modelLineChartOption.series[0].data = this.analyticsData.modelLineChartOption.map(item => item.viewCount);

                    // 下面的代码是防止dom元素还未加在就去根据id获取元素，以及防止获取到错误的元素
                    this.$nextTick(() => {
                        if (document.getElementById('modelLineChart')) {
                            this.renderModelLineChart();
                        }
                        if (document.getElementById('exhibitionLineChart')) {
                            this.renderExhibitionLineChart();
                        }
                        if (document.getElementById('modelPieChart')) {
                            this.renderModelPieChart();
                        }
                        if (document.getElementById('categoryPieChart')) {
                            this.renderCategoryPieChart();
                        }
                        if (document.getElementById('exhibitionPieChart')) {
                            this.renderExhibitionPieChart();
                        }
                    });

                    this.closeLoading()
                }
            } catch (err) {
                this.$message.error('请求出错了：' + err);
            }
        },
        getRandomColor() {
            // 如果没有可用颜色，重置颜色数组
            if (this.availableColors.length === 0) {
                this.availableColors.push('#91CC75', '#FAC858', '#5470C7', '#74C0DE');
            }

            let randomColor;

            // 循环直到找到一个未使用的颜色
            do {
                // 随机选择一个颜色
                const randomIndex = Math.floor(Math.random() * this.availableColors.length);
                randomColor = this.availableColors[randomIndex];

                // 检查颜色是否已经被使用
            } while (this.usedColors.includes(randomColor));

            // 将选中的颜色加入已使用数组
            this.usedColors.push(randomColor);

            // 移除已使用的颜色
            const index = this.availableColors.indexOf(randomColor);
            this.availableColors.splice(index, 1);

            return randomColor;
        },


        closeLoading() {
            this.timer = null;
            this.timer = setTimeout(() => {
                this.loading = false;
            }, 600);
        },

        handleDateChange() {
            // 处理日期筛选
            // 在这里更新数据和重新渲染图表
        },
        selectDate(option) {
            this.selectedButton = option;
            // 根据选中的按钮来更新日期选择器的值
            if (option === 'today') {
                // 设置日期选择器的值为当日的时间范围
                this.init("today");
            } else if (option === 'last7days') {
                // 设置日期选择器的值为最近7天的时间范围
                this.init("last7days");
            } else if (option === 'last30days') {
                // 设置日期选择器的值为最近30天的时间范围
                this.init("last30days");
            } else if (option === 'last60days') {
                // 设置日期选择器的值为最近60天的时间范围
                this.init("last60days");
            } else if (option === 'last90days') {
                // 设置日期选择器的值为最近90天的时间范围
                this.init("last90days");
            } else if (option === 'lastyear') {
                // 设置日期选择器的值为最近一年的时间范围
                this.init("lastyear");
            }
        },
        renderModelLineChart() {
            // 渲染观看数量趋势折线图
            const lineChart = echarts.init(document.getElementById('modelLineChart'));
            // 添加窗口大小改变监听事件，当窗口大小改变时，图表会重新绘制，自适应窗口大小
            window.addEventListener("resize", function () {
                lineChart.resize();
            });
            // 添加折线图配置和数据
            lineChart.setOption(this.modelLineChartOption);
        },
        renderExhibitionLineChart() {
            // 渲染观看数量趋势折线图
            const lineChart = echarts.init(document.getElementById('exhibitionLineChart'));
            // 添加窗口大小改变监听事件，当窗口大小改变时，图表会重新绘制，自适应窗口大小
            window.addEventListener("resize", function () {
                lineChart.resize();
            });
            // 添加折线图配置和数据
            lineChart.setOption(this.exhibitionLineChartOption);
        },

        renderModelPieChart() {
            // 渲染模型喜爱数据饼图
            const modelPieChart = echarts.init(document.getElementById('modelPieChart'));

            // 添加窗口大小改变监听事件
            window.addEventListener("resize", function () {
                modelPieChart.resize();
            });

            // 设置饼图配置
            modelPieChart.setOption(this.modelPieChartOption);
        },
        renderCategoryPieChart() {
            // 渲染类型喜爱数据饼图
            const categoryPieChart = echarts.init(document.getElementById('categoryPieChart'));

            // 添加窗口大小改变监听事件，当窗口大小改变时，图表会重新绘制，自适应窗口大小
            window.addEventListener("resize", function () {
                categoryPieChart.resize();
            });

            // 设置饼图配置
            categoryPieChart.setOption(this.categoryPieChartOption);
        },
        renderExhibitionPieChart() {
            // 渲染类型喜爱数据饼图
            const exhibitionPieChart = echarts.init(document.getElementById('exhibitionPieChart'));

            // 添加窗口大小改变监听事件，当窗口大小改变时，图表会重新绘制，自适应窗口大小
            window.addEventListener("resize", function () {
                exhibitionPieChart.resize();
            });
            exhibitionPieChart.setOption(this.exhibitionPieChartOption);
        },
    },

};
</script>
  
<style scoped >
/* 添加样式 */
.el-card ::v-deep .el-card__header {
    height: 10%;
    padding-left: 20px;
}

.el-card ::v-deep .el-card__body {
    display: grid;
    align-items: center;
    height: 90%;
}

.circle-icon1 {
    display: inline-block;
    background-color: #E6FAF0;
    width: 50px;
    height: 50px;
    border-radius: 100%;
    padding: 15px;
}

.circle-icon1 i {
    color: #48D57F;
}

.circle-icon2 {
    display: inline-block;
    background-color: #E8F4FF;
    width: 50px;
    height: 50px;
    border-radius: 100%;
    padding: 15px;
}

.circle-icon2 i {
    color: #0089FF;
}

.circle-icon1 i {
    color: #48D57F;
}

.circle-icon3 {
    display: inline-block;
    background-color: #FFF8E6;
    width: 50px;
    height: 50px;
    border-radius: 100%;
    padding: 15px;
}

.circle-icon3 i {
    color: #FEBA02;
}

.circle-icon4 {
    display: inline-block;
    background-color: #F4F4F4;
    width: 50px;
    height: 50px;
    border-radius: 100%;
    padding: 15px;
}

.circle-icon4 i {
    color: #8D8F96;
}

.card-main {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

}

.listView {

    padding: 10px;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.line1 {
    flex: 1;
    display: flex;
    width: 100%;
    min-height: 60px;
    background: #FFFFFF;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 10px;
}

.line2 {
    flex: 10;
    display: flex;
    width: 100%;
    min-height: 250px;

}

.line3 {
    flex: 20;
    display: flex;
    width: 100%;
    min-height: 460px;
}

.l2Data1 {
    flex: 1;
    margin-right: 20px;
    margin-top: 20px;
}

.l2Data2 {
    flex: 2;
    margin-top: 20px;
}

.l3Data1 {
    flex: 2;
    min-width: 60%;
    margin-right: 20px;
    margin-top: 20px;
    box-sizing: border-box;
}

.l3Data2 {
    flex: 1;
    min-width: 30%;
    margin-top: 20px;
    box-sizing: border-box;
}
</style>